package com.topisv.tms.web.yhd;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.OrdenoSource;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.edi.lead.LeadService;
import com.topisv.tms.utils.lead.LeadUtil;

/**
 * 一号店订单导入
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value = "/yhdLead")
public class YHDLeadController {

	private static final Logger log = LoggerFactory.getLogger(YHDLeadController.class);
	
	private final static String init = "yhd/yhdLeadInit";

	private final static String values = "yhd/yhdLeadEdiOrderValues";
	
	@Autowired
	private CustomersService customersService;
	@Autowired
	private LeadService leadService;

	@RequestMapping(value = "init")
	public String toSynWeightPage(Model model) {
		ShiroUser user = getShiroUser();
		List<Customers> customers=customersService.loadCustomerByAuthority(user);
		List<OrdenoSource> sources=customersService.findOrdenoSource(customers.get(0).getCustomerCode());
		model.addAttribute("sources", sources);
		model.addAttribute("customers", customers);
		return init;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "lead/{type}")
	public String syn(@PathVariable(value = "type") String type, Model model,
			ServletRequest request, RedirectAttributes redirectAttributes) {
		HttpServletRequest httpRequest = null;
		DiskFileItemFactory factory = null;
		ServletFileUpload upload = null;
		List<FileItem> items = null;
		Workbook rwb = null;
		try {
			log.info("订单导入开始");
			httpRequest = (HttpServletRequest) request;
			httpRequest.setCharacterEncoding("UTF-8");
			factory = new DiskFileItemFactory();
			upload = new ServletFileUpload(factory);

			items = upload.parseRequest(httpRequest);
			Iterator<FileItem> itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				if (item.isFormField()) {

				} else {
					if (item.getName() != null && !item.getName().equals("")) {
						List<EdiOrder> ediOrders = new ArrayList<EdiOrder>();
						// 获取Excel文件对象
						InputStream stream = item.getInputStream();

						if (item.getName().endsWith(".xls")) {// 解析xls
							rwb = new HSSFWorkbook(stream);
							int count = rwb.getNumberOfSheets();
							for (int i = 0; i < count; i++) {
								Sheet sheet = rwb.getSheetAt(i);
								int rows=sheet.getLastRowNum();//.getRows();
								if(rows>0){
									ediOrders.addAll(LeadUtil.setEdiOrder(null,sheet));
								}
							}
						} else if (item.getName().endsWith(".xlsx")) {// 解析xlsx
							rwb = new XSSFWorkbook(stream);
							int count = rwb.getNumberOfSheets();
							for (int i = 0; i < count; i++) {
								XSSFSheet sheet = (XSSFSheet) rwb.getSheetAt(i);
								int rows=sheet.getLastRowNum();//.getRows();
								if(rows>0){
									ediOrders.addAll(LeadUtil.setEdiOrder(null,sheet));
								}
							}
						}
						Map<String, EdiOrder> maps = LeadUtil.getEdiOrders(ediOrders);// 订单汇总
						log.info("总共导入订单数量:"+maps.size());
						Map<String, List<EdiOrder>> mapEdiOrders=null;
						try {
							mapEdiOrders=leadService.saveHS(maps.values(), type);
							model.addAttribute("normal", mapEdiOrders.get("normal"));
							model.addAttribute("exception", mapEdiOrders.get("exception"));
							model.addAttribute("suspect", mapEdiOrders.get("suspect"));
							model.addAttribute("message", "订单导入成功");
							model.addAttribute("status", "1");
							model.addAttribute("number",maps.size());
							log.info("导入成功");
						} catch (Exception e) {
							model.addAttribute("normal", new ArrayList<EdiOrder>());
							model.addAttribute("exception", new ArrayList<EdiOrder>());
							model.addAttribute("suspect", new ArrayList<EdiOrder>());
							model.addAttribute("message", e.getMessage());
							model.addAttribute("status", "1");
							model.addAttribute("number",0);
							log.error("导入失败:"+e.getMessage());
							
						}
						
					} else {
						model.addAttribute("message", "没有选择同步文件！");
					}
				}
			}
		} catch (Exception e) {
			
			model.addAttribute("message", "同步数据失败！");
			log.info("导入失败");
		}
		return values;
	}
	
	/**
	 * 取出Shiro中的当前用户Id.
	 */
	private ShiroUser getShiroUser() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user;
	}
}
